# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import datetime
import pymysql


class OtPipeline(object):

    cursor = ''

    def __init__(self):
        config = {
            'host': '127.0.0.1',
            'port': 3306,
            'user': 'root',
            'passwd': 'root',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor
        }
        conn = pymysql.connect(**config)
        conn.autocommit(1)
        DB_NAME = 'test'
        conn.select_db(DB_NAME)
        self.cursor = conn.cursor()

    def process_item(self, item, spider):
        # 存储数据
        title = item['title']
        price = float(item['price'].replace(',',''))
        scan_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        #print('start：入库 %s' % title)
        self.cursor.execute("insert into otc(title,price,scan_time) values('%s','%f','%s')" %(title,price,scan_time))

        # print('=== item ====')
        # print(item)
        return item
